package org.ytor.core.aspect;

import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.ytor.common.anno.Limit;
import org.ytor.common.enums.DateUnit;
import org.ytor.common.exception.BaseException;
import org.ytor.common.util.Strs;
import org.ytor.common.util.cache.C;
import org.ytor.core.holder.U;
import org.ytor.core.util.ReqUtil;
import org.ytor.core.util.RespUtil;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * created by yangtong on 2025/4/12 09:15:31
 * <br/>
 * 幂等性切面
 */
@Aspect
@Component
public class LimitAspect {

    //强制使用本地缓存记录用户请求时间
//    @Autowired
//    private ICache cacheByLocal;

    private static final String LIMIT_KEY_PREFIX = "limit";
    private static final Logger log = LoggerFactory.getLogger(LimitAspect.class);

    @Pointcut("@annotation(org.ytor.common.anno.Limit)")
    public void logPointcut() {
    }

    @Before("logPointcut()")
    public void around(JoinPoint joinPoint) {
        //获取当前用户信息和请求信息
        HttpServletRequest request = ReqUtil.getRequest();
        String authorization = U.token();
        if (request == null || authorization == null) {
            throw new BaseException("登录状态异常");
        }

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取限流信息
        Limit limit = method.getAnnotation(Limit.class);
        if (limit == null) {
            return;
        }
        String value = limit.value();
        if (Strs.isEmpty(value)) {
            value = request.getMethod() + "::" + request.getRequestURI();
        }
        long minInterval = limit.minIntervalMillis();
        int maxCalls = limit.maxCalls();
        long timeWindow = limit.timeWindowMillis();

        String key = LIMIT_KEY_PREFIX + "::" + authorization + "::" + value;

        //执行限流逻辑
        long now = System.currentTimeMillis();
        TimestampList timestamps = C.get(key, TimestampList.class, TimestampList::new, -1, DateUnit.MS);
        if (timestamps.isEmpty()) {
            timestamps.addLast(now);
            return;
        }

        // 移除超过时间窗口的调用记录
        while (!timestamps.isEmpty() && (now - timestamps.peekFirst()) > timeWindow) {
            timestamps.pollFirst();
        }
        if (timestamps.isEmpty()) {
            timestamps.addLast(now);
            return;
        }

        //检查最近一次调用
        long lastTime = timestamps.peekLast();
        if ((now - lastTime) < minInterval) {
            throw new BaseException("调用太频繁");
        }

        // 检查五分钟内的调用次数
        if (timestamps.size() >= maxCalls) {
            throw new BaseException(Strs.format("调用太频繁，{}分钟内最多调用{}次", (timeWindow / 1000 / 60), maxCalls));
        }
        timestamps.addLast(now);
    }

    static class TimestampList extends ConcurrentLinkedDeque<Long> {
        // 可加构造函数、工具方法等
    }

}
